<template>
  <el-card class="box-card">
    <el-button type="primary" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <el-table :data="tableData" border style="margin: 10px 0px; width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template #="{ row }">
          <img :src="row.logoUrl" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="address" label="品牌操作">
        <template #="{ row, index }">
          <el-button
            type="warning"
            size="small"
            icon="Edit"
            @click="udateTrademark(row)"
          ></el-button>
          <el-popconfirm
            :title="`您确定删除${row.tmName}`"
            width="250px"
            icon="delete"
            @confirm="removeTrademark(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      background
      :page-sizes="[3, 7, 9, 15]"
      layout=" prev, pager, next, jumper,->, sizes, total,"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="dataList"
    />
  </el-card>
  <!-- 新增和编辑 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      :model="trademarkParams"
      :label-width="formLabelWidth"
      :rules="rules"
      ref="formRef"
    >
      <el-form-item label="品牌名称" placeholder="请输入品牌名称" prop="tmName">
        <el-input v-model="trademarkParams.tmName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="品牌logo" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <UploadFilled />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confrim">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import {
  trademarkList,
  addOrUpdate,
  deleteTrademark,
} from '@/api/product/trademark'
import type { Records, ListData, trademark } from '@/api/product/trademark/type'
const pageNo = ref<number>(1)
const limit = ref<number>(3)
const total = ref<number>(0)
const tableData = ref<Records>([])
const dialogFormVisible = ref<boolean>(false)
const formLabelWidth = ref<string>('90px')
const formRef = ref()
const trademarkParams = reactive<trademark>({
  tmName: '',
  logoUrl: '',
})

const rules = {
  tmName: [{ required: true, trigger: 'blur', message: '品牌名称不能为空' }],
  logoUrl: [{ required: true, trigger: 'change', message: '品牌logo不能为空' }],
}
const dataList = async (pager = 1) => {
  pageNo.value = pager
  const res: ListData = await trademarkList(pageNo.value, limit.value)
  if (res.code == 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
dataList()

const handleSizeChange = (val: number) => {
  dataList()
}
// 添加品牌
const addTrademark = () => {
  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''

  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
}
//
// 弹框的确定按钮
const confrim = async () => {
  await formRef.value.validate()
  const res = await addOrUpdate(trademarkParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    dataList(trademarkParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? res.data : '添加品牌失败',
    })
  }
  dialogFormVisible.value = false
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  trademarkParams.logoUrl = response.data
}
// 上传图片之前
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的文件大小应小于4M',
      })
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件类型必须是PNG|JPG|GIF',
    })
    return false
  }
}

// 编辑修改品牌
const udateTrademark = (row: trademark) => {
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })

  Object.assign(trademarkParams, row)
}
// 删除品牌
const removeTrademark = async (id: number) => {
  const res = await deleteTrademark(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    //再次获取已有的品牌数据
    dataList(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: res.data,
    })
  }
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
